package org.dromara.job.snailjob;

import cn.hutool.json.JSONObject;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.core.util.JsonUtil;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.enums.FormatsType;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.oce.constant.CommonConstantsJuLang;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.mapper.OceAdvertiserReferralRelationMapper;
import org.dromara.oce.service.OceAdvertiserDataAnalysisService;
import org.dromara.oce.service.OceAdvertiserEverydayCostService;
import org.dromara.oce.service.OceEverydayCostHoursService;
import org.dromara.oce.utils.TimeUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * @desc: 广告主数据分析
 * @author: hhl
 * @date：2025/5/19 15:18
 */
@Component
@JobExecutor(name = "advertiserDataAnalysisJob")
@RequiredArgsConstructor
public class AdvertiserDataAnalysisJobExecutor {

    private final OceAdvertiserReferralRelationMapper referralRelationMapper;
    private final ScheduledExecutorService scheduledExecutorService;
    private final OceAdvertiserDataAnalysisService oceAdvertiserDataAnalysisService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        SnailJobLog.REMOTE.info("advertiserDataAnalysisJob. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
        JSONObject jsonObject = new JSONObject(JsonUtil.toJsonString(jobArgs));
        String jobParamStr = jsonObject.getStr("jobParams");
        List<String> params = null;
        String lastStr = null;
        String lastTime = null;
        //分批处理
        int batchSize; //每批次处理的大小
        if(StringUtils.isNotBlank(jobParamStr)){
            params = Arrays.asList(jobParamStr.split("_"));
        }
        if(CollectionUtils.isNotEmpty(params)){
            batchSize = Integer.parseInt(params.get(0));
            if(params.size() > 1){
                lastStr = params.get(1);
            }
            if(params.size() > 2){
                lastTime = params.get(2);
            }
        } else {
            batchSize = 30;
        }


        Date statDateTemp = new Date();
        List<String> dateList = new ArrayList<>();
        String lastDateStr = null;
        if(StringUtils.equals(lastStr, "1")){
            if(StringUtils.isNotBlank(lastTime)){
                lastDateStr = lastTime;
            }else{
                Date statDateLast = DateUtils.addDays(new Date(),-1);
                lastDateStr = DateUtils.parseDateToStr(FormatsType.YYYY_MM_DD, statDateLast);
            }
            dateList.add(lastDateStr);
        }else{
            dateList.add(DateUtils.parseDateToStr(FormatsType.YYYY_MM_DD, statDateTemp));
        }

        LambdaQueryWrapper<OceAdvertiserReferralRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(OceAdvertiserReferralRelation::getPullStatus, CommonConstantsJuLang.PULL_STATUS_ON);
        List<OceAdvertiserReferralRelation> referralRelations = referralRelationMapper.selectJobList(lqw);
        if (CollectionUtils.isNotEmpty(referralRelations)) {
            // 根据日期拉取每天每小时的消耗数据
            dateList.forEach(date -> {
                SnailJobLog.REMOTE.info("advertiserDataAnalysisJob date " + date);
                // 天的时间戳
                Long dateTimestamp = TimeUtils.getTimestampSecond(date);
                for (int i = 0; i < referralRelations.size(); i += batchSize) {
                    int endIndex = Math.min(i + batchSize, referralRelations.size());
                    List<OceAdvertiserReferralRelation> batchList = referralRelations.subList(i, endIndex);
                    scheduledExecutorService.schedule(() -> {
                        oceAdvertiserDataAnalysisService.syncOceDataAnalysis(batchList,date,dateTimestamp);
                    }, 2, TimeUnit.SECONDS);
                }
            });
        }
        return ExecuteResult.success("广告主数据分析同步执行成功!");
    }
}
